package com.wr.interceptor;

import com.wr.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 王瑞
 * @description:
 * @date 2020/2/23  21:48
 */

public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Boolean re = false;
        HttpSession session = request.getSession();
        //每次访问之前 所有的handler都要走这个拦截器
        //拦截器在session中判断是否有用户信息 如果有 就放行 如果没有 就跳转到登录页面要求登录
        User user = (User) session.getAttribute("user");
        if (user!=null){
            re = true;
        }else {
            //如果没登录 跳转登录页面
            response.sendRedirect("/login/toLogin");
        }

        return re;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
